<template>
  <div class="out" v-loading="loading" element-loading-text="加载中...">
    <div class="btns">
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="addType"> 添加出入库类型</HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="ids.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1, '要启用出入库类型')">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2, '要禁用出入库类型')">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(3, '要删除出入库类型')">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-select
          v-model="storeListSearch.type"
          class="mr5 w100"
          @keyup.enter="getListStoreType"
          clearable
          placeholder="入库/出库"
        >
          <el-option label="入库" :value="1" />
          <el-option label="出库" :value="2" />
        </el-select>

        <el-input
          v-model="storeListSearch.name"
          class="mr5 w100"
          @keyup.enter="getListStoreType"
          clearable
          placeholder="出入库类型名称"
          @clear="getListStoreType"
        >
        </el-input>
        <div class="filter">
          <el-button type="primary" color="#007cff" class="search_btn" @click="getListStoreType">
            <el-icon class="mr5">
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button class="reset_btn" @click="clearVlaue">
            <el-icon class="mr5">
              <RefreshRight />
            </el-icon>
            重置
          </el-button>
        </div>
      </div>
    </div>

    <div class="table-list">
      <el-table
        :border="true"
        @selection-change="handleChange"
        :data="tableDataList"
        stripe
        resizable
        style="position: absolute"
        height="100%"
      >
        <template #empty>
          <el-empty description="暂无数据" :image-size="140" />
        </template>
        <el-table-column type="selection" width="40" fixed />
        <el-table-column type="index" label="序号" width="50" fixed />
        <el-table-column show-overflow-tooltip prop="name" label="出入类型名称" />
        <el-table-column show-overflow-tooltip prop="status" label="类型" width="70">
          <template #default="scope">
            <span>{{ scope.row.type == 1 ? '入库' : '出库' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工单配件入库" prop="inStoreOrderSpareType" width="130">
          <template #default="scope">
            <span style="display: flex; justify-content: center; gap: 5px; align-items: center">
              <el-switch disabled v-model="scope.row.inStoreOrderSpareType" size="small" />
              <span v-if="scope.row.inStoreOrderSpareType">开启</span>
              <span v-else>关闭</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="工单配件出库" prop="outStoreOrderSpareType" width="130">
          <template #default="scope">
            <span style="display: flex; justify-content: center; gap: 5px; align-items: center">
              <el-switch disabled v-model="scope.row.outStoreOrderSpareType" size="small" />
              <span v-if="scope.row.outStoreOrderSpareType">开启</span>
              <span v-else>关闭</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus type="info" v-if="scope.row.status">禁用</HStatus>
            <HStatus v-else>启用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="130" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="130" />
        <el-table-column show-overflow-tooltip fixed="right" label="操作" width="60">
          <template #default="scope">
            <HLink @click="getDetailStoreItem(scope.row.id)">编辑</HLink>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getListStoreType"
        @current-change="getListStoreType"
      />
    </div>

    <!-- 添加仓库类型弹窗 -->
    <HModal v-model="addDialog" :title="storeForm.id ? '编辑仓库类型' : '添加仓库类型'" width="500">
      <div class="cards">
        <el-form
          ref="ruleFormRef"
          :model="storeForm"
          label-position="right"
          :rules="rulesStore"
          label-width="110"
          class="modal_form_content"
          @validate="handleFormValidate"
        >
          <!-- 出入库类型 -->
          <el-form-item label="出入库类型" class="form_radio_group_item">
            <el-radio-group v-model="storeForm.type" :disabled="!!storeForm.id">
              <el-radio :value="1">入库</el-radio>
              <el-radio :value="2">出库</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 出入库类型名称 -->
          <el-form-item
            label="出入库类型名称"
            prop="name"
            class="form_input_item"
            :class="{ error_form_item: !formValidateResult['name'] }"
          >
            <el-input v-model="storeForm.name" clearable placeholder="类型名称" maxlength="30" />
          </el-form-item>

          <!-- 工单配件出库 -->
          <el-form-item label="工单配件出库" v-if="storeForm.type == 2" class="form_switch_item">
            <div class="switch_container">
              <el-switch v-model="storeForm.outStoreOrderSpareType" />
              <span v-if="storeForm.outStoreOrderSpareType" class="text">开启</span>
              <span v-else class="text">关闭</span>
            </div>
          </el-form-item>

          <!-- 工单配件入库 -->
          <el-form-item label="工单配件入库" v-else class="form_switch_item">
            <div class="switch_container">
              <el-switch v-model="storeForm.inStoreOrderSpareType" />
              <span v-if="storeForm.inStoreOrderSpareType" class="text">开启</span>
              <span v-else class="text">关闭</span>
            </div>
          </el-form-item>

          <!-- 状态 -->
          <el-form-item label="状态" class="form_switch_item">
            <div class="switch_container">
              <el-switch v-model="storeForm.status" />
              <span v-if="storeForm.status" class="text">启用</span>
              <span v-else class="text">禁用</span>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footerRight>
        <HButton is-modal type="primary" @click="submitForm">保存</HButton>
        <HButton is-modal @click="closeClick">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive } from 'vue'
  import Pagination from '@/components/Pagination/index.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    getStoreTypeList,
    addStoreType,
    deleteStoreType,
    disableStoreType,
    getDetailStoreType,
  } from '@/api/store'
  import * as _ from 'lodash'
  import {
    RefreshRight,
    Search,
    Delete,
    Warning,
    CircleCheck,
    ArrowDown,
  } from '@element-plus/icons-vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/service/common/useFormValidate/useFormValidateService'

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService([
      { name: 'name', isSelect: false },
      { name: 'outStoreExample', isSelect: true },
    ])

  const total = ref(0)
  const loading = ref(false)
  const pagination = ref()
  const tableDataList = ref([])
  let ids = ref([])
  // 仓库列表搜索对象
  const storeListSearch = ref({
    page: 1,
    limit: 50,
    name: '',
    type: null,
  })
  const storeForm = ref({
    id: null,
    name: '',
    status: true, //仓库类型状态：false-启用，true-禁用 渲染取反
    type: 2, //	类型：1-入库，2-出库,示例值(2)
    outStoreOrderSpareType: false, // 是默认为工单配件出库类型：false-否，true-是
    inStoreOrderSpareType: false, // 是默认为工单配件入库类型：false-否，true-是
  })
  const addDialog = ref(false)
  const ruleFormRef = ref()
  const rulesStore = reactive({
    name: [{ required: true, message: '请输入仓库名称', trigger: ['blur', 'change'] }], //仓库名称
    outStoreExample: [{ required: true, message: '仓库类型', trigger: ['blur', 'change'] }], //仓库类型：false-内部仓库，true-外部仓库
  })
  // 获取类型列表
  const getListStoreType = () => {
    loading.value = true
    storeListSearch.value.page = pagination.value.current // 当面页码
    storeListSearch.value.limit = pagination.value.size // 当面页码

    getStoreTypeList(storeListSearch.value).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          tableDataList.value = res.data.data.rows
          total.value = Number(res.data.data.total)
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 4000,
              offset: 200,
            })
        }
      }
      loading.value = false
    })
  }
  const addType = () => {
    storeForm.value = {
      id: null,
      name: '',
      status: true, //仓库类型状态：false-启用，true-禁用 渲染取反
      type: 2, //	类型：1-入库，2-出库,示例值(2)
      outStoreOrderSpareType: false, // 是默认为工单配件出库类型：false-否，true-是
      inStoreOrderSpareType: false, // 是默认为工单配件入库类型：false-否，true-是
    }
    addDialog.value = true
  }
  // 保存添加仓库类型
  const submitForm = _.debounce(async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid) => {
      if (valid) {
        loading.value = true
        let ValueData = _.cloneDeep(storeForm.value)
        ValueData.status = !storeForm.value.status // 取反
        addStoreType(ValueData).then((res) => {
          if (res) {
            if (res.data.code == 20000) {
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'success',
                duration: 4000,
                offset: 200,
              })
              getListStoreType()
              closeClick()
            } else {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: 'error',
                  duration: 4000,
                  offset: 200,
                })
            }
          }
          loading.value = false
        })
      }
    })
  }, 600)
  // 根据仓库ID获取仓库详情
  const getDetailStoreItem = async (storeId: string) => {
    loading.value = true
    await getDetailStoreType(storeId).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          const data = res.data.data.row
          storeForm.value = { ...data, status: !data.status }
          addDialog.value = true
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 4000,
              offset: 200,
            })
        }
      }
    })
    loading.value = false
  }
  // 关闭取消
  const closeClick = () => {
    resetFormValidateResult()
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
    addDialog.value = false
  }
  // 批量删除、启用、禁用
  async function changeAll(n: number, str: string) {
    if (ids.value.length == 0) {
      ElMessage({
        message: `请先选择要操作的选项`,
        type: 'warning',
        duration: 2000,
        offset: 200,
      })
      return
    }
    ElMessageBox({
      title: '提示',
      message: `确定${str}?`,
      showCancelButton: true,
      closeOnClickModal: false,
      type: n === 3 ? 'error' : 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
    })
      .then(async () => {
        loading.value = true
        switch (n) {
          case 1:
          case 2:
            await disableStoreType(ids.value, n == 1 ? false : true).then((res) => {
              if (res) {
                if (res.data.code == 20000) {
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: 'success',
                    offset: 200,
                  })
                  getListStoreType()
                } else {
                  if (res.data.isError)
                    ElMessage({
                      showClose: true,
                      message: res.data.message,
                      type: 'error',
                      offset: 200,
                    })
                }
              }
              loading.value = false
            })
            break
          case 3:
            await deleteStoreType(ids.value).then((res) => {
              if (res) {
                if (res.data.isError)
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: res.data.success ? 'success' : 'error',
                    offset: 200,
                  })
                if (res.data.code == 20000) {
                  ids.value = []
                  getListStoreType()
                }
              }
              loading.value = false
            })
            break
        }
      })
      .catch()
  }
  // 选择批量操作的id
  function handleChange(val) {
    ids.value = []
    val.filter((o) => {
      ids.value.push(o.id)
    })
  }
  // 重置
  const clearVlaue = () => {
    storeListSearch.value.name = ''
    storeListSearch.value.type = null
  }
  onMounted(() => {
    getListStoreType()
  })
</script>

<style scoped lang="scss">
  :deep(.el-radio__input.is-disabled) {
    span {
      background: #f5f7fa !important;
      border-color: #e4e7ed !important;
    }

    span.el-radio__label {
      span {
        color: #999 !important;
      }
    }
  }

  :deep(.el-radio.is-disabled.is-checked) {
    span {
      color: #999 !important;
    }
  }

  /* @import '../../index.scss'; */
  .out {
    display: flex;
    flex-direction: column;
    flex: 1;
    .table-list {
      flex: 1;
      position: relative;
    }
    .footer {
      display: flex;
      justify-content: flex-end;
      margin-top: 12px;
    }

    .btns {
      margin: 10px 0;
      display: flex;
      justify-content: space-between;

      .mr5 {
        margin-right: 5px;
      }

      .btn_btn {
        display: flex;
        align-items: center;
      }

      .search {
        display: flex;
        align-items: center;

        .w100 {
          width: 150px;
        }

        .btn {
          display: flex;
          align-items: center;
        }
      }
    }
  }
</style>
